package com.zyh.em.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTest {
    public static void main(String[] args) {

        //正则表达式
        final String regex = "INFO\\s+(\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2})\\s+([a-z0-9\\u4e00-\\u9fa5]*)\\s+(EVALUATE)\\s+\\[([a-z0-9\\u4e00-\\u9fa5]*)\\]\\s+([a-z0-9]{32})\\s+\\\"([a-z0-9\\.\\-\\,]{6,12})\\\"\\s+([a-z\\u4e00-\\u9fa5]*)\\s+\\\"([0-9\\.\\,]*)\\\"\\s+\\[([0-9\\,\\.]*)\\]\\s+\\\"(.*)\\\"";

        //表示的是日志
        final String string = "INFO 2020-06-19 10:23:16 WebApplication EVALUATE [zhangsan] 119e76e86bea42e9a098c2461a6b9314 \"123456\" Zhengzhou \"113.65,34.76\" [1500,2800,3100] \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\"";

        //通过正则表达式以及匹配模式，生成的pattern对象
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);

        //pattern对需要处理的字符串进行匹配，生成的matcher
        final Matcher matcher = pattern.matcher(string);

        //通过matcher.find()确定字符串是否和正则表达式能够匹配上
        //如果匹配上就返回true，否则就返回false
        //如果能匹配上，就回去每一组的数据：0组表示所有数据，从1到组的个数分别获取对应组的数据
        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));

            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}
